<template>
  <div class="user-manage">
    <el-card>
      <div class="header-bar">
        <span>用户列表</span>
        <div>
          <el-button type="primary" size="small" @click="openAddUser">新增用户</el-button>
          <el-button type="warning" size="small" @click="goToBlacklist">黑名单管理</el-button>
        </div>
      </div>
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="60"/>
        <el-table-column prop="name" label="用户名"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <span>
              {{
                scope.row.role === 1 ? '管理员' :
                    scope.row.role === 2 ? '发货人员' :
                        '普通人员'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="openEditUser(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteUser(scope.row)">删除</el-button>
            <add-to-blacklist-button
                :user-id="scope.row.id"
                :user-name="scope.row.name"
                @success="fetchUsers"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="userDialogVisible" :title="userForm.id ? '编辑用户' : '新增用户'">
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.name"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userForm.password"/>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="userForm.phone"/>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" :value="1"/>
            <el-option label="发货人员" :value="2"/>
            <el-option label="普通人员" :value="3"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getUserList, addUser, updateUser, deleteUser} from '@/api/admin/user'
import AddToBlacklistButton from '@/components/AddToBlacklistButton.vue'
import {useRouter} from 'vue-router'

const router = useRouter()
const userList = ref([])
const userDialogVisible = ref(false)
const userForm = ref({id: null, name: '', studentId: '', email: '', phone: '', role: ''})

const fetchUsers = async () => {
  const res = await getUserList()
  if (res.code === 200) {
    userList.value = res.data
  }
}

const openAddUser = () => {
  userForm.value = {id: null, name: '', studentId: '', email: '', phone: '', role: ''}
  userDialogVisible.value = true
}

const openEditUser = (row) => {
  let roleNum = row.role
  if (roleNum === 'admin' || roleNum === 2 || roleNum === '2') roleNum = 2
  else if (roleNum === 'leader' || roleNum === 1 || roleNum === '1') roleNum = 1
  else roleNum = 0
  userForm.value = {...row, role: roleNum}
  userDialogVisible.value = true
}

const handleSaveUser = async () => {
  if (!userForm.value.name || !userForm.value.role) {
    ElMessage.warning('用户名和角色不能为空')
    return
  }
  let res
  if (userForm.value.id) {
    res = await updateUser(userForm.value)
  } else {
    res = await addUser(userForm.value)
  }
  if (res.code === 200) {
    ElMessage.success('保存成功')
    userDialogVisible.value = false
    fetchUsers()
  } else {
    ElMessage.error(res.msg || '保存失败')
  }
}

const handleDeleteUser = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteUser(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchUsers()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {
  })
}

const goToBlacklist = () => {
  router.push('/admin/blackuser')
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
